package org.example.myleet.hash;

import org.example.myleet.Utils.Assert;

import java.util.HashMap;
import java.util.Map;

public class HashSolution {

    /**
     * 1410【模拟+RabinKarp哈希】HTML 实体解析器
     */
    public String entityParser(String text) {
        Map<Long, Character> hashVMapChar = new HashMap<>(6);
        hashVMapChar.put(238909428L, '"');
        hashVMapChar.put(205273075L, '\'');
        hashVMapChar.put(1603312L, '&');
        hashVMapChar.put(13300L, '>');
        hashVMapChar.put(13940L, '<');
        hashVMapChar.put(27621095916L, '/');
        char[] charArr = text.toCharArray();
        StringBuilder sb = new StringBuilder();
        int i = 0, n = text.length();
        while (i < n) {
            char ci = charArr[i];
            if (ci == '&') {
                int j = i + 1, k = 0;
                char cj;
                long hashV = 0L;
                for (; j < n; ++j) {
                    cj = charArr[j];
                    if (cj == ';' || k >= 5) break;
                    hashV = hashV * 128 + cj;
                    ++k;
                }
                Character ch = hashVMapChar.get(hashV);
                if (null != ch) {
                    sb.append(ch);
                    i = j + 1;
                    continue;
                }
            }
            sb.append(ci);
            ++i;
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        HashSolution solution = new HashSolution();
        Assert.isTrue("& is an HTML entity but &ambassador; is not.".equals(solution.entityParser("&&&&amp; is a&gt;n H&apos;&quot;TML ent&lt;ity but &amba&frasl;&fras&frasl;l;ssador; is not.")));
        Assert.isTrue("& is an HTML entity but &ambassador; is not.".equals(solution.entityParser("&amp; is an HTML entity but &ambassador; is not.")));
    }
}
